package com.wxit.gulimall.product.web;

import com.wxit.gulimall.product.entity.CategoryEntity;
import com.wxit.gulimall.product.service.CategoryService;
import com.wxit.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author wj
 * @date 2022.02.17 16:46
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;

    //String[] value() default {}
    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){

        //TODO 查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();

        /**
         * public static final String DEFAULT_PREFIX = "classpath:/templates/"; 默认前缀
         * public static final String DEFAULT_SUFFIX = ".html";  默认后缀
         * 视图解析器进行拼串 classpath:/templates/ + 反回值 + .html
         */
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }


    //index/catalog.json
    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatelogJson(){
        Map<String, List<Catelog2Vo>> catelogJson = categoryService.getCatelogJson();
        return catelogJson;
    }



    @GetMapping("/hello")
    @ResponseBody
    public String hello(){

        //获取一把锁,只要锁的名字一样，就是同意把锁
        RLock lock = redisson.getLock("my-lock");

        //加锁
        lock.lock();
        try {
            System.out.println("加锁成功，执行业务" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e){

        } finally {
            //解锁
            System.out.println("释放锁---" + Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }


    /**
     * 保证一定能读到最新的数据，修改期间，写锁是一个排他锁(互斥锁),读锁是一个共享锁，写锁没释放，读锁就必须等待
     * @return
     */
    @GetMapping("/write")
    @ResponseBody
    public String writeValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try {
            //1.改数据加写锁，读数据加读锁
            rLock.lock();
            System.out.println("写锁加锁成功...." + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("写锁释放成功" + Thread.currentThread().getId());
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        //加读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            System.out.println("读锁加锁成功" + Thread.currentThread().getId());
            s = redisTemplate.opsForValue().get("writeValue");
            Thread.sleep(30000);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("读锁释放成功" + Thread.currentThread().getId());
        }
        return s;
    }

    /**
     * 闭锁
     *
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await(); //等待闭锁都完成
        return "开始放假...";
    }

    @GetMapping("/gogo/{id}")
    @ResponseBody
    public String gogo(@PathVariable("id") Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown(); //计数减一
        return id + "班的人扯呼了...";
    }


    /**
     * 信号量
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
//        park.acquire();//获取一个信号
        boolean b = park.tryAcquire();
        return  "ok==>" + b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go(){
        RSemaphore park = redisson.getSemaphore("park");
        park.release();//释放一个信号
        return "ok";
    }
}
